/**
 * Copyright (c) 2019-2029, wwww.kiwipeach.cn (liuburu@qq.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * https://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.github.toucan.demo.cmd;

import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.Size;
import org.springframework.shell.standard.ShellComponent;
import org.springframework.shell.standard.ShellMethod;
import org.springframework.shell.standard.ShellOption;

import java.util.List;

@ShellComponent("入门级命令")
public class DemoCommands {

    /**
     * 使用两种命令中的任意一种都可以
     * 例：printVersion -C  或 printVersion --command
     *
     * @param command 命令参数
     * @return 返回字符串
     */
    @ShellMethod(value = "打印版本号", key = "printVersion", group = "calc")
    public String printVersion(@ShellOption({"-C", "--command"}) String command) {
        return command;
    }


    /**
     * 自定义分组，命令关键字
     * 例：sum | sum 1 9 | sum --a 1 --b 9
     *
     * @param a a参数
     * @param b b参数
     * @return 返回两个数的和
     */
    @ShellMethod(value = "求两数之和", key = "sum", prefix = "--", group = "calc")
    public String add(@ShellOption(value = "--a", defaultValue = "1", help = "第一个参数") int a,
                      @ShellOption(value = "--b", defaultValue = "-1", help = "第二个参数") int b) {
        return String.format("%s + %s = %s", a, b, a + b);
    }

    /**
     * 命令行参数基本校验,可选参数以及必填参数（默认必填）
     *
     * @param userName 用户名
     * @return 返回密码信息
     */
    @ShellMethod(value = "用户名长度校验", key = "uCheck", prefix = "--", group = "user")
    public String userNameLenCheck(@ShellOption(value = "--uName", help = "用户名") @NotEmpty @Size(min = 6, max = 20) String userName,
                                   @ShellOption(defaultValue = "no email info.", help = "邮箱") String email) {
        int len = userName.length();
        return String.format("用户信息(用户名：%s 邮箱：%s)是否合法? %s", userName, email, (len >= 6 && len < 20));
    }

    /**
     * 验证参数列表
     * 例：
     * xPlus-shell:>sumAll 1 2 3
     * [1, 2, 3] 之和为: 6
     * xPlus-shell:>sumAll -p 1 2 3
     * [1, 2, 3] 之和为: 6
     *
     * @param params 参数信息
     * @return 返回参数列表之和
     */
    @ShellMethod(value = "参数列表之和", key = "sumAll", group = "calc")
    public String parameterList(@ShellOption(arity = 3, value = "-p") List<Integer> params) {
        int sum = 0;
        for (int item : params) {
            sum += item;
        }
        return String.format("%s 之和为: %s", params.toString(), sum);
    }

}
